package core.domain.util;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import core.domain.IdEntity;
import core.domain.exception.InvalidVersionException;

public class DomainUtils {

	public static Class<?> getSingleParameterClass(Class<?> input) {
		Type superClassType = input.getGenericSuperclass();
		if (null == superClassType) {
			throw new IllegalArgumentException("Invalid input class !");
		}
		while (!(superClassType instanceof ParameterizedType)) {
			input = input.getSuperclass();
			superClassType = input.getGenericSuperclass();
		}
		if (superClassType instanceof ParameterizedType) {
			ParameterizedType pt = (ParameterizedType) superClassType;
			return (Class<?>) pt.getActualTypeArguments()[0];
		} else {
			throw new IllegalArgumentException(input.getName());
		}
	}

	public static void checkFrmVersion(IdEntity entity, long frmVersion) {
		if (entity.getVersion() != frmVersion) {
			throw new InvalidVersionException(
					"Persistent root version conflict detected: (referenceVersion = "
							+ frmVersion + ", frmVersion = "
							+ entity.getVersion() + ")");
		}
	}
}
